<!-- 新增编辑发文 -->
<template>
  <div class="app-container" :style="height">
    <el-row>
      <el-col :span="12">
        <el-form ref="form" :model="form" class="work-search-form" :rules="rules" label-width="120px">
          <el-form-item label="题目" prop="title">
            <el-input v-model="form.title" placeholder="请输入题目" />
          </el-form-item>
          <el-form-item label="主送单位" prop="hostUnit">
            <treeselect v-model="form.hostUnit"
            :options="deptOptions"
            :disable-branch-nodes="false"
            :show-count="true"
            @select="selectHostUnit"
            placeholder="请选择主送单位" />
          </el-form-item>
          <el-form-item label="抄送单位(多个)" prop="copyUnit">
            <treeselect v-model="form.copyUnit"
            :options="deptOptions"
             :multiple="true"
            :show-count="true"
            @select="selectCopyUnit"
            @deselect="deselectCopyUnit"
            @input="inputselectCopyUnit"
            placeholder="请选择抄送单位(多个)" />
          </el-form-item>
          <el-form-item label="报送单位(多个)" prop="submittedUnit">
            <treeselect v-model="form.submittedUnit"
            :options="deptOptions"
             :multiple="true"
            :show-count="true"
            @select="selectSubmittedUnit"
            @deselect="deselectSubmittedUnit"
            @input="inputselectSubmittedUnit"
            placeholder="请选择报送单位(多个)" />
          </el-form-item>
          <el-form-item label="缓急程度" prop="pressing">
            <el-select v-model="form.pressing" placeholder="请选择缓急程度">
              <el-option
                v-for="dict in degreeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="密级" prop="security">
            <el-select v-model="form.security" placeholder="请选择密级">
              <el-option
                v-for="dict in secretLevelOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item label="字号" prop="number">
            <el-input v-model="form.number" placeholder="请输入字号" />
          </el-form-item>
          <el-form-item label="份数" prop="part">
            <el-input v-model="form.part" placeholder="请输入份数" />
          </el-form-item>
          <el-form-item label="拟稿单位" prop="drafterUnit">
            <treeselect v-model="form.drafterUnit"
            :options="deptOptions"
            :disable-branch-nodes="false"
            :show-count="true"
            @select="selectDrafterUnit"
            placeholder="请选择拟稿单位" />
          </el-form-item>
          <el-form-item label="拟稿人" prop="draftert">
            <el-select v-model="form.draftert" filterable placeholder="请选择拟稿人">
              <el-option
                v-for="dict in userList"
                :key="dict.user_id"
                :label="dict.user_name"
                :value="dict.user_name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="核稿人" prop="proofreading">
            <el-select v-model="form.proofreading" filterable placeholder="请选择核稿人">
              <el-option
                v-for="dict in userList"
                :key="dict.user_id"
                :label="dict.user_name"
                :value="dict.user_name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="打号人" prop="markingPerson">
            <el-select v-model="form.markingPerson" filterable placeholder="请选择打号人">
              <el-option
                v-for="dict in userList"
                :key="dict.user_id"
                :label="dict.user_name"
                :value="dict.user_name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="核对人" prop="check">
            <el-select v-model="form.check" filterable placeholder="请选择核对人">
              <el-option
                v-for="dict in userList"
                :key="dict.user_id"
                :label="dict.user_name"
                :value="dict.user_name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="封发日期" prop="dispatchingTime">
            <el-date-picker
              v-model="form.dispatchingTime"
              type="date"
              format="yyyy-MM-dd" value-format="yyyy-MM-dd"
              placeholder="选择封发日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="form.remark" placeholder="请填写备注" />
          </el-form-item>
          <el-form-item label="附件">
            <el-upload
              ref="upload"
              :action="upload.url"
              :headers="upload.headers"
              multiple
              :file-list="upload.fileList"
              :on-success="annexSuccess"
              :before-upload="beforeAttachmentUpload"
              :before-remove="beforeRemove"
              :on-remove="annexRemove">
              <el-button slot="trigger" size="small" type="primary">添加附件</el-button>
              <div slot="tip" style="color: #999; font-size: 12px;"
              v-text="'支持'+fileUploadParams.fileType+'，且不超过'+fileUploadParams.fileSize+'MB'"></div>
            </el-upload>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer" style="text-align:center">
      <!-- <el-button type="primary" @click="printTable">打 印</el-button> -->
      <template v-if="!params.isEdit">
        <el-button type="primary" :loading="submitLoading" @click="submitForm(1)">提 交</el-button>
      </template>
      <el-button type="primary" :loading="submitLoading" @click="submitForm(2)">保 存</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
  import {addPostProcessSheet,addEditPostProcessSheet,detailsPostProcessSheet,deptProcessModel,getUserList } from "@/api/system/postProcessSheetManage";
  import { treeselectStatus } from "@/api/system/dept";
  import { getToken } from "@/utils/auth";
  import { fileUploadParams,getFileNameSuffix,getNowDateTime } from "@/utils/ruoyi"
  // import { treeselect } from "@/api/system/statute";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  export default {
    name: "AddEditPost",
    components: {
      Treeselect
    },
    data() {
      return {
        height: "max-height:"+((document.documentElement.clientHeight || document.body.clientHeight)-110)+"px;overflow-y:auto",
        params: {
          isEdit: false,
        },
        form: {},
        fileUploadParams: fileUploadParams(),
        userInfo: JSON.parse(this.$store.getters.userInfo),
        // 缓急程度数据字典
        degreeOptions: [],
        // 密级数据字典
        secretLevelOptions: [],
        //部门列表
        deptList: [],
        // 部门树选项
        deptOptions: undefined,
        //用户列表
        userList: [],
        // 部门列表
        //menuOptions: [],
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 表单校验
        rules: {
          title: [{ required: true, message: "请输入题目", trigger: "blur" }],
          number: [{ required: true, message: "请输入字号", trigger: "blur" }],
          pressing: [{ required: true, message: "请选择缓急程度", trigger: "change" }],
          //security: [{ required: true, message: "请选择密级", trigger: "change" }],
          hostUnit: [{ required:true, message:'请选择主送单位', trigger:"change" }],
          copyUnit: [{ required:true, message:'请选择抄送单位', trigger:"change" }],
          submittedUnit: [{ required:true, message:'请选择报送单位', trigger:"change" }],
          drafterUnit: [{ required:true, message:'请选择拟稿单位', trigger:"change" }],
          draftert: [{ required:true, message:'请选择拟稿人', trigger:"change" }],
          proofreading: [{ required:true, message:'请选择核稿人', trigger:"change" }],
          check: [{ required:true, message:'请选择核对人', trigger:"change" }],
          markingPerson: [{ required:true, message:'请选择打号人', trigger:"change" }],
          dispatchingTime: [{ required:true, message:'请选择封发日期', trigger:"change" }],
          part: [{ required:true, message:'请输入份数', trigger:"blur" }]
          // title: undefined,    //题目
          // number: undefined,   //字号
          // pressing: undefined, //缓急程度
          // security: undefined, //密级
          // hostUnit: undefined, //主送单位
          // copyUnit: undefined, //抄送单位
          // submittedUnit: undefined, //报送单位
          // drafterUnit: undefined, //拟稿单位
          // proofreading: undefined, //核稿人
          // markingPerson: undefined, //打号人
          // check: undefined, //核对人
          // dispatchingTime: undefined, //封发日期
          // part: undefined, //份数
        },
        upload: {
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/common/upload",
          // 上传的文件列表
          fileList: [],
        },
        //表单提交加载项
        submitLoading: false
      }
    },
    created() {
      if(this.$route.params && this.$route.params.docId>0){
        this.$route.meta.title = '编辑发文处理单'
        this.$store.state.tagsView.visitedViews[this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path)].title = '编辑发文处理单'
      }else{
        this.$route.meta.title = '新建发文处理单'
        this.$store.state.tagsView.visitedViews[this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path)].title = '新建发文处理单'
      }
      this.reset();
      this.form.dispatchingTime = getNowDateTime();
      const id = this.$route.params && this.$route.params.docId;
      this.params = this.$route.params;
      //查询部门下拉树结构
      this.getTreeselect()
      //获取单位列表
      this.getDeptList()
      //获取用户列表
      this.getUserList()
      if(id && id > 0){
        detailsPostProcessSheet({id:id}).then((res)=>{
          this.form = res.data
          //特殊处理  抄送单位，报送单位
          if(this.form.copyUnit){
            this.form.copyUnit = this.form.copyUnit.split(',')
          }
          if(this.form.submittedUnit){
            this.form.submittedUnit = this.form.submittedUnit.split(',')
          }
          if(this.form.copyUnitName){
            this.form.copyUnitName = this.form.copyUnitName.split(',')
          }
          if(this.form.submittedUnitName){
            this.form.submittedUnitName = this.form.submittedUnitName.split(',')
          }
          //获取文件列表数据
          this.$nextTick(() => {
            const arr = [];
            if (this.form.attachmentName != null){
              var attachmentName = this.form.attachmentName.split(",");
              var attachmentUrl = this.form.attachmentUrl.split(",");
              var attachmentPath = this.form.attachmentPath.split(",");
              for (var k=0;k<attachmentName.length;k++){
                arr.push({
                  name:attachmentName[k],
                  response:{
                    fileName:attachmentPath[k],
                    url:attachmentUrl[k],
                  }
                });
              }
            }
            this.upload.fileList=arr;
            this.form.fileList=arr;
          });
          this.$nextTick(()=>{
            this.$refs['form'].clearValidate()
          })
          console.log(this.form)
        })
      }
      this.getDicts("degree_urgency").then(response => {
        this.degreeOptions = response.data;
      });
      this.getDicts("secret_level").then(response => {
        this.secretLevelOptions = response.data;
      });
      //this.getMenuTreeselect();
      // if (row!=null && row!=undefined && row!=''){
      //   this.form = row;
      //   this.form.announcementType = ''+this.form.announcementType+'';
      //   this.$nextTick(() => {
      //     const arr = [];
      //     if (this.form.receiveUserId != null){
      //       var userids = this.form.receiveUserId.split(",");
      //       for (var k=0;k<userids.length;k++){
      //         arr.push(parseInt(userids[k]));
      //       }
      //     }
      //     this.$refs.menu.setCheckedKeys(userids);//获取已经设置的资源后渲染
      //   });
      //   this.$nextTick(() => {
      //     const arr = [];
      //     if (row.attachmentName != null){
      //       var attachmentName = row.attachmentName.split(",");
      //       var attachmentUrl = row.attachmentUrl.split(",");
      //       var attachmentPath = row.attachmentPath.split(",");
      //       for (var k=0;k<attachmentName.length;k++){
      //         arr.push({
      //           name:attachmentName[k],
      //           response:{
      //             fileName:attachmentPath[k],
      //             url:attachmentUrl[k],
      //           }
      //         });
      //       }
      //     }
      //     this.upload.fileList=arr;
      //     this.form.fileList=arr;
      //   });
      // }
    },
    methods: {
      /** 查询部门下拉树结构 */
      getTreeselect() {
        var params = { status: 0 };
        treeselectStatus(params).then(response => {
          this.deptOptions = response.data;
        });
      },
      //获取单位列表
      getDeptList(){
        deptProcessModel().then((res)=>{
          if(res.code == 200){
            this.deptList = res.data
          }
        })
      },
      /** 转换机构数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.label,
          children: node.children
        };
      },
      /** 主送单位触发事件 */
      selectHostUnit(node, instanceId){
        if(node && node.label){
          this.form.hostUnitName = node.label
        }
      },
      /** 抄送单位选中选项触发事件 */
      selectCopyUnit(node, instanceId){
        if(node && node.label){
          this.form.copyUnitName.push(node.label)
        }
      },
      /** 抄送单位取消选项触发事件 */
      deselectCopyUnit(node, instanceId){
        if(this.form.copyUnitName && this.form.copyUnitName.length>0){
          var arr = []
          for(var i=0;i<this.form.copyUnitName.length;i++){
            if(this.form.copyUnitName[i] != node.label){
              arr.push(this.form.copyUnitName[i])
            }
          }
          this.form.copyUnitName = arr
        }
        if(this.form.copyUnit && this.form.copyUnit.length>0){
          var arr2 = []
          for(var i=0;i<this.form.copyUnit.length;i++){
            if(this.form.copyUnit[i] != node.id){
              arr2.push(this.form.copyUnit[i])
            }
          }
          this.form.copyUnit = arr2
          this.$set(this.form, 'copyUnit', arr2)
        }
      },
      inputselectCopyUnit(value, instanceId){
        if(value.length == 0){
          this.form.copyUnitName = []
        }
        console.log(this.form.copyUnit)
      },
      /** 报送单位触发事件 */
      selectSubmittedUnit(node, instanceId){
        if(node && node.label){
          this.form.submittedUnitName.push(node.label)
        }
      },
      /** 报送单位取消选中触发事件 */
      deselectSubmittedUnit(node, instanceId){
        if(this.form.submittedUnitName && this.form.submittedUnitName.length>0){
          var arr = []
          for(var i=0;i<this.form.submittedUnitName.length;i++){
            if(this.form.submittedUnitName[i] != node.label){
              arr.push(this.form.submittedUnitName[i])
            }
          }
          this.form.submittedUnitName = arr
        }
        if(this.form.submittedUnit && this.form.submittedUnit.length>0){
          var arr2 = []
          for(var i=0;i<this.form.submittedUnit.length;i++){
            if(this.form.submittedUnit[i] != node.id){
              arr2.push(this.form.submittedUnit[i])
            }
          }
          this.form.submittedUnit = arr2
          this.$set(this.form, 'submittedUnit', arr2)
        }
      },
      inputselectSubmittedUnit(value, instanceId){
        if(value.length == 0){
          this.form.submittedUnitName = []
        }
      },
      /** 拟稿单位触发事件 */
      selectDrafterUnit(node, instanceId){
        if(node && node.label){
          this.form.drafterUnitName = node.label
        }
      },
      //获取用户列表
      getUserList(){
        getUserList().then((res)=>{
          if(res.code == 200){
            this.userList = res.data
          }
        })
      },
      // 表单重
      // 表单重置
      reset() {
        if (this.$refs.menu != undefined) {
          this.$refs.menu.setCheckedKeys([]);
        }
        this.form = {
          id: undefined,
          title: undefined,    //题目
          number: undefined,   //字号
          pressing: undefined, //缓急程度
          //security: undefined, //密级
          hostUnit: undefined, //主送单位
          hostUnitName: undefined, //主送单位名称
          copyUnit: undefined, //抄送单位
          copyUnitName: [], //抄送单位名称
          submittedUnit: undefined, //报送单位
          submittedUnitName: [], //抄送单位名称
          drafterUnit: undefined, //拟稿单位
          drafterUnitName: undefined, //拟稿单位名称
          draftert: undefined,  //拟稿人
          proofreading: undefined, //核稿人
          markingPerson: undefined, //打号人
          check: undefined, //核对人
          dispatchingTime: undefined, //封发日期
          part: undefined, //份数
          remark: undefined,
          applyDepartment: this.userInfo.dept.deptId,
          fileList: [],
        };
        this.upload.fileList = [];
        this.resetForm("form");
        this.$nextTick(()=>{
          this.$refs['form'].clearValidate()
        })
      },
      // 取消按钮
      cancel() {
        this.$router.go(-1);// 返回
        //关闭子页面
        this.$store.state.tagsView.visitedViews.splice(this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path), 1);
        var view = {
          name: 'PostProcessSheetManage',
        }
        this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {
          this.$router.push({
            name: 'PostProcessSheetManage',
          });
        })
      },
      /** 提交按钮 */
      submitForm:function(statu) {
        this.$refs["form"].validate(valid => {
          if (valid) {
            var params = Object.assign({}, this.form)
            //特殊处理抄送单位ID
            if(params.copyUnit && params.copyUnit.length>0){
              params.copyUnit = params.copyUnit.join(',')
            }
            //特殊处理抄送单位名称
            if(params.copyUnitName && params.copyUnitName.length>0){
              params.copyUnitName = params.copyUnitName.join(',')
            }
            //特殊处理报送单位ID
            if(params.submittedUnit && params.submittedUnit.length>0){
              params.submittedUnit = params.submittedUnit.join(',')
            }
            //特殊处理报送单位名称
            if(params.submittedUnitName && params.submittedUnitName.length>0){
              params.submittedUnitName = params.submittedUnitName.join(',')
            }
            if(statu == 1){
              //提交并启动流程
              this.submitLoading = true
              addPostProcessSheet(params).then((res)=>{
                this.submitLoading = false
                if (res.code === 200) {
                  this.msgSuccess("新增并启动流程成功");
                  this.cancel();
                }
              }).catch(()=>{
                this.submitLoading = false
              });
            }else if(statu == 2){
              //保存新增/编辑
              this.submitLoading = true
              addEditPostProcessSheet(params).then(res => {
                this.submitLoading = false
                if (res.code === 200) {
                  this.msgSuccess("保存成功");
                  this.cancel();
                }
              }).catch(()=>{
                this.submitLoading = false
              });
            }
          }
        });
      },
      // 跳转到打印单页面
      printTable(){
        this.$store.dispatch('tagsView/delView', {'name':'PrintPost'}).then(({ visitedViews }) => {
          this.$router.push({
            name: 'PrintPost'
          });
        })
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.msgSuccess(response.msg);
        this.$alert(response.url, '视频地址', {
          dangerouslyUseHTMLString: true
        });
      },
      // 附件上传成功处理
      annexSuccess(response, file, fileList) {
        console.log('附件上传成功处理')
        console.log(response)
        console.log(file)
        console.log(fileList)
        this.form.fileList=fileList
      },
      // 上传之前的处理
      beforeAttachmentUpload(file, fileList){
        var isTrue = true
        var fileTypeVerify = this.fileUploadParams.fileType
        var fileSuffix = getFileNameSuffix(file)
        if(fileTypeVerify.indexOf(fileSuffix) > -1){
          isTrue = true
        }else{
          this.msgError('支持'+this.fileUploadParams.fileType+'，且不超过'+this.fileUploadParams.fileSize+'MB')
          isTrue = false
        }
        return isTrue;
      },
      //移除文件之前的处理
      beforeRemove(file, fileList){
        let a = true;
        if (file && file.status==="success") {
            a = this.$confirm(`确定移除 ${ file.name }？`);
        }
        return a;
      },
      // 附件上传移除
      annexRemove(file, fileList) {
        console.log(fileList)
        if(file && file.status == "success"){
          this.form.fileList=fileList
          var arr = []
          var arr2 = []
          console.log(this.upload.fileList)
          console.log(this.form.fileList)
          // this.upload.fileList=arr;
          // this.form.fileList=arr;
          // for(var i=0;i<this.form.enclosure_url.length;i++){
          //   if(file.uid != this.form.enclosure_url[i].uid){
          //     arr.push(this.form.enclosure_url[i])
          //     arr2.push(this.form.enclosureUrl[i])
          //   }
          // }
          // this.form.enclosureUrl = arr2
          // this.form.enclosure_url = arr
        }
      },
      /** 查询菜单树结构 */
      // getMenuTreeselect() {
      //   treeselect().then(response => {
      //     this.menuOptions = response.data;
      //   });
      // },
      // 所有人员节点数据
      getMenuAllCheckedKeys() {
        // 目前被选中的菜单节点
        let checkedKeys = this.$refs.menu.getHalfCheckedKeys();
        // 半选中的菜单节点
        let halfCheckedKeys = this.$refs.menu.getCheckedKeys();
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
        return checkedKeys;
      },
      // 类型字典翻译
      typeFormat(row, column) {
        return this.selectDictLabel(this.typeOptions, row.announcementType);
      },
    }
  }
</script>
